<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  
  <title>jvm篇之垃圾回收器g1 | JAVA</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="垃圾回收器">
  
  
  
  
  <meta name="description" content="背景G1（Garbage-First）是一款面向服务端应用的垃圾收集器，主要针对配备多核CPU及大容量内存的机器，以极高概率满足GC停顿时间的同时，还兼具高吞吐量的性质。 在JDK1.7版本正式启动，移除了Experimental的标识，是JDK9以后的默认垃圾回收器，取代了CMS回收器以及Parallel组合，被Oracle官方称为“全功能垃圾收集器”。 特点分代收集  从分代上看，G1依然属于">
<meta name="keywords" content="垃圾回收器">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM篇之垃圾回收器G1">
<meta property="og:url" content="https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/index.html">
<meta property="og:site_name" content="JAVA">
<meta property="og:description" content="背景G1（Garbage-First）是一款面向服务端应用的垃圾收集器，主要针对配备多核CPU及大容量内存的机器，以极高概率满足GC停顿时间的同时，还兼具高吞吐量的性质。 在JDK1.7版本正式启动，移除了Experimental的标识，是JDK9以后的默认垃圾回收器，取代了CMS回收器以及Parallel组合，被Oracle官方称为“全功能垃圾收集器”。 特点分代收集  从分代上看，G1依然属于">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/image-20201231110613736.png">
<meta property="og:image" content="https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/image-20201231114119798.png">
<meta property="og:updated_time" content="2021-02-06T07:22:21.334Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JVM篇之垃圾回收器G1">
<meta name="twitter:description" content="背景G1（Garbage-First）是一款面向服务端应用的垃圾收集器，主要针对配备多核CPU及大容量内存的机器，以极高概率满足GC停顿时间的同时，还兼具高吞吐量的性质。 在JDK1.7版本正式启动，移除了Experimental的标识，是JDK9以后的默认垃圾回收器，取代了CMS回收器以及Parallel组合，被Oracle官方称为“全功能垃圾收集器”。 特点分代收集  从分代上看，G1依然属于">
<meta name="twitter:image" content="https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/image-20201231110613736.png">
  
    <link rel="alternate" href="/atom.xml" title="JAVA" type="application/atom+xml">
  

  

  <link rel="icon" href="/css/images/mylogo.jpg">
  <link rel="apple-touch-icon" href="/css/images/mylogo.jpg">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt; src:url("/css/fonts/FuturaPTBold.otf") format("woff");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt-light; src:url("/css/fonts/FuturaPTBook.otf") format("woff");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt-italic; src:url("/css/fonts/FuturaPTBookOblique.otf") format("woff");font-weight:400;font-style:italic;}
}

  </style>
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>
  <script src="/js/bootstrap.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css">

  
    <link rel="stylesheet" href="/css/dialog.css">
  

  

  
    <link rel="stylesheet" href="/css/header-post.css">
  

  
  
  
    <link rel="stylesheet" href="/css/vdonate.css">
  

</head>
</html>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  
  <div id="container">
    <div id="wrap">
      
        <header>

    <div id="allheader" class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-inner">
          
          <div class="container"> 
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>

            
              <a class="brand" style="border-width: 0;">
                <p>JAVA</p>
              </a>
            
            
            <div class="navbar-collapse collapse">
              <ul class="hnav navbar-nav">
                
                  <li> <a class="main-nav-link" href="/">首页</a> </li>
                
                  <li> <a class="main-nav-link" href="/archives">归档</a> </li>
                
                  <li> <a class="main-nav-link" href="/categories">分类</a> </li>
                
                  <li> <a class="main-nav-link" href="/tags">标签</a> </li>
                
                  <li> <a class="main-nav-link" href="/about">关于</a> </li>
                
                  <li><div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder>
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词...">
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(无标题)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div></li>
            </ul></div>
          </div>
                
      </div>
    </div>

</header>



      
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-JVM篇之垃圾回收器G1" style="width: 75%; float:left;" class="article article-type-post" itemscope itemprop="blogPost">
  <div id="articleInner" class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" itemprop="name">
      JVM篇之垃圾回收器G1
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	<a href="/2020/12/31/JVM篇之垃圾回收器G1/" class="article-date">
	  <time datetime="2020-12-31T02:10:36.000Z" itemprop="datePublished">2020-12-31</time>
	</a>

      
    <a class="article-category-link" href="/categories/JVM/">JVM</a>

      
	<a class="article-views">
	<span id="busuanzi_container_page_pv">
		阅读量<span id="busuanzi_value_page_pv"></span>
	</span>
	</a>

      

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h2><p>G1（Garbage-First）是一款面向服务端应用的垃圾收集器，主要针对配备多核CPU及大容量内存的机器，以极高概率满足GC停顿时间的同时，还兼具高吞吐量的性质。</p>
<p>在JDK1.7版本正式启动，移除了Experimental的标识，是JDK9以后的默认垃圾回收器，取代了CMS回收器以及Parallel组合，被Oracle官方称为“全功能垃圾收集器”。</p>
<h2 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h2><p>分代收集</p>
<ul>
<li>从分代上看，G1依然属于分代型垃圾回收器，它会区分年轻代和老年代，年轻代依然有Eden区和Survivor区。从堆的结构上看，他不要求整个Eden区，Old区都是固定的，也不再坚持固定大小和固定数量。</li>
<li>将堆空间划分若干个区域，这些区域中包括了逻辑上年轻代和老年代。</li>
</ul>
<p>空间整合</p>
<ul>
<li>G1将内存划分为一个个的region，内存回收以region作为基本单位。Region之间是复制算法，但整体上实际可以看做标记-压缩算法。两种算法都可以避免内存碎片化。这种特性有利于程序长时间运行，分配大对象时不会因为无法找到连续内存空间而提前触发下一次GC。尤其当Java堆非常大时候，G1优势更加明显。</li>
</ul>
<p>可预测模型</p>
<p>G1除了追求低停顿外，还能建立可预测模型的停顿时间，能让使用者明确规定在一个长度为M毫秒的时间片段内，消耗在垃圾收集上的时间不得超过N毫秒。</p>
<ul>
<li>由于分区原因，G1可以只选取部分区域进行内存回收，这样缩小了回收的范畴，因此在全局停顿的情况下也能较好的控制</li>
<li>G1跟踪各个region里面的垃圾堆积的价值大小（回收所获得的空间大小和回收所需时间经验值），在后台维护一个优先列表，每次根据允许的收集时间，优先回收价值最大的region。保证了G1收集器在有限时间内可以获得尽可能高的收集效率。</li>
</ul>
<h2 id="分区Region"><a href="#分区Region" class="headerlink" title="分区Region"></a>分区Region</h2><p>使用G1收集器，它将整个java堆划分约2048个大小相同独立Region块，每个Region块大小根据堆空间的实际大小而定，整体被控制在1MB到32MB之间，且为2的N次幂，即1MB、2MB、4MB、8MB、16MB、32MB。可以通过-XX:C1HeapRegionSize设定，所有的Region大小相同，且在JVM生命周期内不会被改变。</p>
<img src="https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/image-20201231110613736.png" alt="image-20201231110613736" style="zoom: 67%;">

<ul>
<li>一个region有可能属于Eden,Survivor或者Old内存区域。但一个region只能属于一个角色。</li>
<li>G1还增加一个新的内存区域，叫做Humongous内存区域，主要存储大对象。</li>
</ul>
<p>设置H的原因</p>
<blockquote>
<p>对于堆中的大对象，默认直接分配到老年代，但是如果它是一个短期存在的大对象，就会占用老年代内存。为了解决这个问题，G1划分了一个Humongous区，它用来专门存放大对象。如果一个H区装不下一个大对象，那么G1会寻找连续H区来存储。</p>
</blockquote>
<h2 id="垃圾回收过程"><a href="#垃圾回收过程" class="headerlink" title="垃圾回收过程"></a>垃圾回收过程</h2><p>G1垃圾回收主要包括以下3个环节</p>
<ul>
<li>年轻代GC</li>
<li>老年代并发标记过程</li>
<li>混合回收</li>
<li>失败保护机制（Full GC）</li>
</ul>
<p><strong>总体概况</strong></p>
<p>当年轻代的Eden区用尽时开始年轻代回收；G1暂停所有应用程序线程，启动多线程执行年轻代回收。年轻代区间存活对象移动到survivor区或者old；当堆内存使用达到一定值（默认45）时，开始老年代并发标记过程。标记完成马上开始混合回收过程。对于一个混合回收期，G1从老年代移动存活对象到空闲区，G1老年代回收不需要整个老年代被回收，一次只需要扫描/回收一小部分老年代的region即可。</p>
<p><strong>Remembered Set</strong></p>
<p>存在一个Region中的对象被其它任意Region对象引用，避免扫描整个java堆。</p>
<p>每个Region都有一个对应Remembered Set;记录其它对象对自己的引用。</p>
<img src="https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/image-20201231114119798.png" alt="image-20201231114119798" style="zoom: 50%;">

<h2 id="常用的设置"><a href="#常用的设置" class="headerlink" title="常用的设置"></a>常用的设置</h2><ul>
<li><strong>-XX:+UseG1GC</strong> 手动指定使用G1收集器执行内存回收任务</li>
<li><strong>-XX:G1HeapRegionSize</strong> 设置Region的大小，值是2的幂，范围是1MB到32MB之间，目标是根据最小堆可以划分约2048个区域，默认是堆内存的1/2000。</li>
<li><strong>-XX:MaxGCPauseMillis</strong> 设置期望达到的最大GC停顿时间指标（JVM会尽力实现，但不能保证成功），默认值200ms</li>
<li><strong>-XX:ParallelGCThead</strong> 设置STW工作线程数的值，最多设置为8</li>
<li><strong>-XX:ConcGCThreads</strong> 设置并发标记的线程数</li>
<li><strong>-XX:InitiatingHeapOccupancyPercent</strong> 设置触发并发GC周期的Java堆占用率阈值，超过此值，就触发GC。默认值是45。</li>
</ul>
<h2 id="操作方法"><a href="#操作方法" class="headerlink" title="操作方法"></a>操作方法</h2><ul>
<li>开启G1垃圾收集器</li>
<li>设置堆最大内存</li>
<li>设置停顿时间</li>
</ul>
<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><ul>
<li>面向服务端应用，针对具有大内存、多处理器的机器</li>
</ul>

      
    </div>
    <footer class="article-footer">
      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: '打赏支持', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://raw.githubusercontent.com/iTimeTraveler/iTimeTraveler.github.io/site/source/about/donate/images/WeChanQR.png',
  alipayImage: 'https://raw.githubusercontent.com/iTimeTraveler/iTimeTraveler.github.io/site/source/about/donate/images/AliPayQR.jpg'
});
</script>
      
      
      <div>
        <ul class="post-copyright">
          <li class="post-copyright-author">
          <strong>本文作者:  </strong>LeBron Tao
          </li>
          <li class="post-copyright-link">
          <strong>本文链接:  </strong>
          <a href="/2020/12/31/JVM篇之垃圾回收器G1/" target="_blank" title="JVM篇之垃圾回收器G1">https://jameslin23.gitee.io/2020/12/31/JVM篇之垃圾回收器G1/</a>
          </li>
          <li class="post-copyright-license">
            <strong>版权声明:   </strong>
            本博客所有文章除特别声明外，均采用 <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-ND 4.0</a>
            许可协议。转载请注明出处
          </li>
         
        </ul>
<div>
</div></div>
      
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8yOTQ4MS82MDQ5">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>



      
      
        
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/垃圾回收器/">垃圾回收器</a></li></ul>

      

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2021/01/03/ThreadLocal/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          ThreadLocal
        
      </div>
    </a>
  
  
    <a href="/2020/12/31/JVM篇之垃圾回收器CMS/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">JVM篇之垃圾回收器CMS</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="toc-sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    
        <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#特点"><span class="nav-number">2.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分区Region"><span class="nav-number">3.</span> <span class="nav-text">分区Region</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#垃圾回收过程"><span class="nav-number">4.</span> <span class="nav-text">垃圾回收过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常用的设置"><span class="nav-number">5.</span> <span class="nav-text">常用的设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#操作方法"><span class="nav-number">6.</span> <span class="nav-text">操作方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#应用场景"><span class="nav-number">7.</span> <span class="nav-text">应用场景</span></a></li></ol>
    
    </div>
  </aside>

</section>
        
      </div>
      
      <footer id="footer">
  

  <div class="container">
      	<div class="row">
	      <p> Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> and <a href="https://github.com/iTimeTraveler/hexo-theme-hiker" target="_blank">Hexo-theme-hiker</a> </p>
	      <p id="copyRightEn">Copyright &copy; 2013 - 2021 JAVA All Rights Reserved.</p>
	      
	      
    		<p class="busuanzi_uv">
				访客数 : <span id="busuanzi_value_site_uv"></span> |  
				访问量 : <span id="busuanzi_value_site_pv"></span>
		    </p>
  		   
		</div>

		
  </div>
</footer>


<!-- min height -->

<script>
    var wrapdiv = document.getElementById("wrap");
    var contentdiv = document.getElementById("content");
    var allheader = document.getElementById("allheader");

    wrapdiv.style.minHeight = document.body.offsetHeight + "px";
    if (allheader != null) {
      contentdiv.style.minHeight = document.body.offsetHeight - allheader.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    } else {
      contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    }
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>




  <script src="/js/dialog.js"></script>








	<div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2 class="modal-title" id="myModalLabel">设置</h2>
      </div>
      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">


      <div class="modal-body">
          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" onclick="javascript:setFontSize();" aria-expanded="true" aria-controls="collapseOne">
              正文字号大小
            </a>
          </div>
          <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            您已调整页面字体大小
          </div>
        </div>
      


          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" onclick="javascript:setBackground();" aria-expanded="true" aria-controls="collapseTwo">
              夜间护眼模式
            </a>
        </div>
          <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
          <div class="panel-body">
            夜间模式已经开启，再次单击按钮即可关闭 
          </div>
        </div>

        <div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关 于&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
        </div>
         <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
          <div class="panel-body">
            JAVA
          </div>
          <div class="panel-body">
            Copyright © 2021 LeBron Tao All Rights Reserved.
          </div>
        </div>
      </div>


      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
    </div>
  </div>
</div>
  
  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
  
    <a id="menu-switch"><i class="fa fa-bars fa-lg"></i></a>
  
</body>
</html>